package com.itany.boot.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.boot.constant.DictConstant;
import com.itany.boot.dao.ResourceMapper;
import com.itany.boot.entity.Resource;
import com.itany.boot.exception.RequestParameterErrorException;
import com.itany.boot.service.ResourceService;
import com.itany.boot.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @author 黄衡熙
 * @version 1.0
 */
//注解bean
@Service
//管理事务
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    public PageInfo<Resource> findByParams(Resource resourceParam, String pageNo, String pageSize) {
        if(ParameterUtil.isNull(pageNo)){
            pageNo= DictConstant.Resource_DEFAULT_PAGE_NO;
        }
        if(ParameterUtil.isNull(pageSize)){
            pageSize=DictConstant.Resource_DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        List<Resource> resources=resourceMapper.selectByParams(resourceParam);
        PageInfo<Resource> resourcePage=new PageInfo<>(resources);
        return resourcePage;
    }


    @Override
    public void modifyStatus(String id, String status) throws RequestParameterErrorException {
        if(ParameterUtil.isNull(id)||ParameterUtil.isNull(status)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        Resource resource=new Resource();
        resource.setId(Integer.parseInt(id));
        resource.setStatus(Integer.parseInt(status));
        if(resource.getStatus()==DictConstant.Resource_STATUS_ENABLED){
            resource.setStatus(DictConstant.Resource_STATUS_DISABLED);
        }else {
            resource.setStatus(DictConstant.Resource_STATUS_ENABLED);
        }
        resourceMapper.updateByPrimaryKeySelective(resource);

    }

    @Override
    public Resource findById(String id) {
        if (ParameterUtil.isNull(id)) {
            return null;
        }
        return resourceMapper.selectByPrimaryKey(Integer.parseInt(id));
    }
    @Override
    public void downloadResource(String id, HttpServletResponse response) throws Exception {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("资源ID不能为空");
        }

        Resource resource = resourceMapper.selectByPrimaryKey(Integer.parseInt(id));
        if (resource == null) {
            throw new RequestParameterErrorException("资源不存在");
        }

        // 获取文件路径
        String filePath = resource.getPath();
        File file = new File(filePath);

        if (!file.exists()) {
            throw new RequestParameterErrorException("文件不存在");
        }

        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + java.net.URLEncoder.encode(resource.getOriginalName(), "UTF-8") + "\"");
        response.setContentLength((int) file.length());

        // 文件下载
        try (InputStream inputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        }
    }
}
